import asyncio
import logging
import threading

import websockets

import getWebsocket

# 给变量加锁
lock = threading.Lock()
loop = None
server = None
response = []
# 存储 WebSocket 连接的集合
connected = set()


def send_message(message):
    if len(connected) > 0:
        lock.acquire()
        response.append(message)
        lock.release()


def del_message(message):
    lock.acquire()
    response.remove(message)
    lock.release()


def clear_message():
    global response
    lock.acquire()
    response = []
    lock.release()


# 定义服务端接收请求的处理方法
async def serve(websocket, path):
    getWebsocket.logger.debug("New client connected")
    connected.add(websocket)
    try:
        while True:
            if len(response) > 0:
                message = response[0]
                new_message = message.replace("'", '"')
                for conn in connected:
                    await conn.send(new_message)
                getWebsocket.logger.debug(f"Send message: {new_message}")
                del_message(message)
            await asyncio.sleep(0.05)
    except websockets.exceptions.ConnectionClosed:
        getWebsocket.logger.debug("Client disconnected")
    except Exception as e:
        getWebsocket.logger.error(e)
    finally:
        connected.remove(websocket)
        print(f'当前连接数{len(connected)}')
        if len(connected) == 0:
            clear_message()
            print('已清空消息列表')


def ws_open_server():
    global loop, server, connected
    connected = set()
    # 在新线程中创建一个新的 event loop
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    # 创建 WebSocket 服务端
    server = websockets.serve(serve, "localhost", 25565)
    getWebsocket.logger.debug("websocket服务端已开启")

    # 启动服务端
    loop.run_until_complete(server)
    loop.run_forever()
    getWebsocket.logger.debug('websocket服务端已关闭')


def ws_close_server():
    global loop, server
    if server is not None:
        getWebsocket.logger.debug("尝试关闭websocket服务端")
        server.ws_server.close()
        loop.call_soon_threadsafe(loop.stop)
